﻿using hlib.IO;
using SalesSys.BLL;
using SalesSys.Comm.BLL;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SalesSys.Site.Controllers.Api
{
    [RoutePrefix("api/Finance")]
    public class FinanceController : BaseApiController
    {
        FinanceBLL financeBLL = BllFactory.GetBll<FinanceBLL>();
        PaymentInfoBLL paymentInfoBLL = BllFactory.GetBll<PaymentInfoBLL>();
        /// <summary>
        /// 报款确认
        /// </summary>
        /// <param name="paymentInfoId">报款编号</param>
        /// <param name="money">报款金额</param>
        /// <param name="pass">是否通过</param>
        /// <param name="approvalRemark">审批备注</param>
        /// <param name="clientId">客户经理</param>
        public void Put(Guid paymentInfoId, decimal money, bool pass, string approvalRemark,Guid clientId)
        {
            financeBLL.PaymentInfoConfirm(paymentInfoId, money, pass, approvalRemark, ClientHelper.ClientInfo.Id, clientId);
        }


        /// <summary>
        /// 退款确认
        /// </summary>
        /// <param name="paymentInfoId">退款单id</param>
        /// <param name="money">金额</param>
        /// <param name="pass">是否通过</param>
        /// <param name="approvalRemark">审批备注</param>
        ///        
        [Route("RefundConfirm")]
        public void RefundConfirm(Guid paymentInfoId, decimal money, bool pass, string approvalRemark)
        {
            financeBLL.RefundConfirm(paymentInfoId, money, pass, approvalRemark, ClientHelper.ClientInfo.Id);
        }

        /// <summary>
        /// 获取报款列表
        /// </summary>
        /// <param name="customerName">客户名称</param>
        /// <param name="accounttype">账户类型</param>
        /// <param name="managerId">申请人编号</param>
        /// <param name="state">审批状态</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("PaymentInfo")]
        public ViewDtos<PaymentInfo> GetPaymentInfo(string customerName = null, FinaceApprovalState? state = null, string accounttype = null, Guid? managerId = null, int page = 1, int rows = 10)
        {
            ViewDtos<PaymentInfo> dto = new ViewDtos<PaymentInfo>();

            var data = paymentInfoBLL.Select(customerName, state, accounttype, GetRequestQuery(), managerId);
            dto.Data = data.Value;
            dto.Total = data.Key;

            dto.Rows = rows;
            dto.Page = page;
            return dto;
        }



        /// <summary>
        /// 查询客户账户流水
        /// </summary>
        /// <param name="customerId">客户编号</param>
        /// <param name="accountId">户头编号</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("List")]
        public ViewDtos<Finance> Get(Guid customerId, Guid? accountId = null, int page = 1, int rows = 10)
        {
            var data = financeBLL.GetFinanceList(customerId, accountId, page, rows);
            var dto = ViewDto.CreateList(data.Value);
            dto.Total = data.Key;
            dto.Rows = rows;
            dto.Page = page;
            return dto;

        }
        /// <summary>
        /// 账户余额退款申请
        /// </summary>
        /// <param name="accountId">账户编号</param>
        /// <param name="money">金额</param>
        public void RefundApproval(Guid accountId, decimal money)
        {
            throw new NotImplementedException();
            financeBLL.RefundApproval(accountId, money, ClientHelper.ClientInfo.Creater);
        }

        /// <summary>
        /// 账户流水导出
        /// </summary>        
        /// <returns></returns>

        [Route("ExpFinance")]
        [HttpGet]
        public HttpResponseMessage ExpFinance()
        {
            var data = financeBLL.GetList(1, 19999);
            HttpResponseMessage msg = null;
            var expData =
                data.Select(
                    p =>
                        new string[]
                        {
                            p.Id.ToString(), p.Account==null?"":p.Account.Name, p.Money.ToString(), p.BeforeAmount.ToString(),
                            p.AfterAmount.ToString(), p.Remark, p.Handler==null?"": p.Handler.Name, p.SourceInfo, p.SourceTag                      
                        });

            var nameArray = new string[] { "id", "户头", "金额", "变动前", "变动后", "备注", "处理人", "信息", "外部编号" };
            msg = CsvExp("客户流水.csv", expData, nameArray);// CreateStreamResponse(sm, "客户流水.csv", false);
            return msg;
        }

        /// <summary>
        /// 款项管理导出
        /// </summary>        
        /// <returns></returns>

        [Route("ExpPaymentInfo")]
        [HttpGet]
        public HttpResponseMessage ExpPaymentInfo()
        {
            var data = paymentInfoBLL.GetList(1, 19999);
            HttpResponseMessage msg = null;
            var expData =
              data.Select(
                  p =>
                      new string[]
                        {
                            p.PaymentStatus==PaymentStatus.Refund?"退款":"报款",p.CustomerAgent.Name,p.Customer.ShortName,p.Account.Name,
                            string.Format("{0:f2}", p.Sum),p.ToAccount,p.CreateTime.ToString("yyyy-MM-dd HH:mm"),p.Remark,p.State.GetDescription()               
                        });

            var nameArray = new string[] { "款项类型", "申请人", "客户", "户头", "金额", "账户", "时间", "备注", "状态" };
            MemoryStream sm = new MemoryStream();
            new CsvWriter(sm).WriteAllLines(expData, nameArray);
            sm.Position = 0;
            msg = CreateStreamResponse(sm, "款项确认.csv", false);
            return msg;
        }
    }
}
